import turtle


class Peano:
    direction = 1
    count = 1

    def swerve(self, length):
        turn(self.direction)
        turtle.forward(length)
        turn(self.direction)
        if self.count % 2 == 1:
            self.direction *= -1
        self.count += 1


# 转向
def turn(s):
    if s == 1:
        turtle.right(90)
    elif s == -1:
        turtle.left(90)


# 第三次时会转向，以2为除数不好计算
def join(tier, length):
    if tier > 0:
        for j in range(1, 10):
            join(tier - 1, length)
            if j == 9:
                break
            elif j % 3 == 0:
                peanoList[tier - 1].swerve(length)
            else:
                turtle.forward(length)


def main():
    turtle.title("皮亚诺曲线")
    width = 900
    height = 800
    startX = 200
    startY = 0
    turtle.setup(width, height, startX, startY)
    turtle.pensize(1)
    turtle.tracer(2)
    turtle.penup()
    turtle.goto(-200, 200)
    turtle.pendown()
    turtle.hideturtle()
    length = 10
    # 阶数
    n = 3
    # 为每个阶层定义类
    for i in range(n):
        peanoList.append(Peano())
    join(n, length)
    turtle.done()


peanoList = []
main()
